from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from django.db import models
from shortuuidfield import ShortUUIDField


class UserManager(BaseUserManager):
    def _create_user(self, username, password, **kwargs):
        if not username:
            raise ValueError('请传入用户名！')
        if not password:
            raise ValueError('请传入密码！')
        user = self.model(username=username, **kwargs)
        user.set_password(password)
        user.save()
        return user

    def create_user(self, username, password, **kwargs):
        kwargs['is_superuser'] = False
        return self._create_user(username, password, **kwargs)

    def create_superuser(self, username, password, **kwargs):
        kwargs['is_superuser'] = True
        kwargs['is_staff'] = True
        return self._create_user(username, password, **kwargs)


class User(AbstractBaseUser, PermissionsMixin):
    # 自定义主键  django-shortuuidfield
    id = ShortUUIDField(primary_key=True)
    username = models.CharField(max_length=100, unique=True)
    telephone = models.CharField(max_length=11, unique=True, null=True, blank=True)
    password = models.CharField(max_length=200)
    avatar = models.URLField(default='/static/images/avatar.png')
    email = models.EmailField(unique=True, blank=True, null=True)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    date_joined = models.DateTimeField(auto_now_add=True)

    # 验证时，使用telephone
    USERNAME_FIELD = 'username'
    # 创建user时，需要填写的字段 USERNAME_FIELD+REQUIRED_FIELDS+password
    REQUIRED_FIELDS = []
    # 发送邮件
    EMAIL_FIELD = 'email'

    objects = UserManager()

    class Meta:
        db_table = 'auth_user'
        verbose_name = '用户表'
        verbose_name_plural = verbose_name

    def get_full_name(self):
        return self.username

    def get_short_name(self):
        return self.username
